package ru.javadevelop.homefinans.activities;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import ru.javadevelop.homefinans.R;

/**
 * http://t-menu.ru
 * User: navff
 * Date: 21.07.12
 * Time: 13:42
 */
public class SettingsActivity extends BaseActivity {

    private EditText editEmailt;
    private EditText editPassword;
    private EditText editUrl;
    private final String SETTINGS_KEY = "Global";

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);

        // Поиск элементов формы
        editEmailt = (EditText)findViewById(R.id.edit_email);
        editPassword  = (EditText)findViewById(R.id.edit_password);
        editUrl = (EditText)findViewById(R.id.edit_server_url);
        // Заполнение элементов формы из настроек
        SharedPreferences mySharedPreferences = getSharedPreferences(SETTINGS_KEY , 0);
        editEmailt.setText(mySharedPreferences.getString("Email", ""));
        editPassword.setText(mySharedPreferences.getString("Password", ""));
        editUrl.setText(mySharedPreferences.getString("Url", ""));

        Button saveButton = (Button)findViewById(R.id.save_settings_button);
        saveButton.setOnClickListener(new SaveSettingsListener());
        editUrl.setOnKeyListener(new EnterUrlListener());
    }

    /**
     * Обработчик нажатия на кнопку «Сохранить»
     */
    private  class SaveSettingsListener implements Button.OnClickListener
    {

        @Override
        public void onClick(View view) {
            if ((editEmailt.getText().toString()=="")||
                (editPassword.getText().toString()=="")||
                (editUrl.getText().toString()==""))
            {
                showMessage(getString(R.string.empty_input_settings), 1300);
                return;
            }
            SharedPreferences mySharedPreferences = getSharedPreferences(SETTINGS_KEY , 0);
            SharedPreferences.Editor editor = mySharedPreferences.edit();
            editor.putString("Email", editEmailt.getText().toString());
            editor.putString("Password", editPassword.getText().toString());
            editor.putString("Url", editUrl.getText().toString());
            editor.commit();

            finish();
        }
    }

    private class EnterUrlListener implements View.OnKeyListener
    {
        @Override
        public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
            if(keyEvent.getAction() == KeyEvent.ACTION_DOWN &&
                    (keyCode == KeyEvent.KEYCODE_ENTER))
            {
                hideKeyboard(editUrl);
            }
            return false;

        }
    }
}
